﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Hospitalbeds;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Hospitalbeds
{
    /// <summary>
    /// 获取病床处理器
    /// </summary>
    public class GetHospitalbedsHandler : IRequestHandler<GetHospitalbedsCommand, APIResult<List<HospitalBedDto>>>
    {
        private readonly IBaseRepository<HospitalBedModel> hospitalBedRepository;
        private readonly IBaseRepository<HospitalRoomModel> hospitalRoomRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetHospitalbedsHandler> logger;

        public GetHospitalbedsHandler(
            IBaseRepository<HospitalBedModel> hospitalBedRepository,
            IBaseRepository<HospitalRoomModel> hospitalRoomRepository,
            IMapper mapper,
            ILogger<GetHospitalbedsHandler> logger)
        {
            this.hospitalBedRepository = hospitalBedRepository;
            this.hospitalRoomRepository = hospitalRoomRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 获取病床信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<HospitalBedDto>>> Handle(GetHospitalbedsCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<HospitalBedDto>> res = new APIResult<List<HospitalBedDto>>();

            try
            {
                // 查询所有未删除的病床
                var query = hospitalBedRepository.GetALL().Where(x => x.IsDeleted == false);

                // 如果指定了病房ID，则按病房ID筛选
                if (request.HospitalRoomId.HasValue)
                {
                    query = query.Where(x => x.HospitalRoomId == request.HospitalRoomId.Value);
                    logger.LogInformation($"查询病房ID为{request.HospitalRoomId.Value}的病床");
                }
                else
                {
                    logger.LogInformation("查询所有病床");
                }

                var hospitalBeds = query.ToList();

                // 获取所有相关的病房信息
                var roomIds = hospitalBeds.Select(x => x.HospitalRoomId).Distinct().ToList();
                var hospitalRooms = hospitalRoomRepository.GetALL()
                    .Where(x => roomIds.Contains(x.Id) && x.IsDeleted == false)
                    .ToDictionary(x => x.Id, x => x);

                // 使用AutoMapper进行映射
                var hospitalBedDtos = mapper.Map<List<HospitalBedDto>>(hospitalBeds);

                // 填充病房号信息
                foreach (var dto in hospitalBedDtos)
                {
                    if (hospitalRooms.TryGetValue(dto.HospitalRoomId, out var room))
                    {
                        dto.HospitalRoomCode = room.HospitalRoomCode;
                    }
                }

                res.Data = hospitalBedDtos;
                res.Code = APIEnums.Success;
                res.Msg = "查询成功";
                logger.LogInformation($"查询病床成功，共查询到{hospitalBedDtos.Count}张病床");
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "查询病床失败";
                logger.LogError(ex, "查询病床时发生异常");
            }

            return Task.FromResult(res);
        }
    }
}